<?php
/**
 * Created by PhpStorm.
 * User: Auser
 * Date: 2017/5/16
 * Time: 19:35
 */

namespace Api\Terrace\Helper;
use Api\Util\Helper;
use Org\Net\Http;
use Think\Cache;
class WxMessageHelper
{
    protected $wxComponentService;

    protected $appId;

    protected $cache;

    protected $weObj;

    public function __construct($obj,$appId,$cache)
    {
        $this->wxComponentService=$obj;
        $this->appId=$appId;
        $this->cache=$cache;
        if (!$this->wxComponentService->isValidAuthorizedAppId($appId)) { // 判断公众号授权是否有效
            Helper::log('=======>testAppId','Wx_ticket');
            Helper::log( "appId:{$appId}, not valid authroized appId param:" . print_r($_GET, true),'Wx_ticket');
            Helper::log('<======testAppId','Wx_ticket');
            die('no access');
        }
        $weObj = $this->wxComponentService->getWechat($this->appId);
        $this->weObj = $weObj;
        if (!$weObj) {
            Helper::log('=======>testweObj','Wx_ticket');
            Helper::log( "appId:{$this->appId}, not valid authroized appId param:" . print_r($_GET, true),'Wx_ticket');
            Helper::log('<======testweObj','Wx_ticket');
            die('no access');
        }
    }

    /**
     *
     */
    public function response_message(){
        $weObj  = $this->weObj;
        $ret = $weObj->valid(true);
        if ($ret === false) {
            die('no access');
        } else if ($ret !== true) {
            die($ret);
        }
        $weObj->getRev();
        $type = $weObj->getRevType();
        Helper::log('<======response_type_' . $type,'Wx_ticket');
        switch($type) {
            case $weObj::MSGTYPE_TEXT :
                $recv_txt = $weObj->getRevContent();
                $weObj->text($recv_txt)->reply('', false);
                 break;
            case $weObj::MSGTYPE_EVENT:
                $data = $weObj->getRevData();
                $ev = $data['Event'];
                $this->geteventmsg($weObj,$this->appId);
                break;
           /* case Wechat::MSGTYPE_IMAGE:

                        break;
            default:
                $weObj->text("help info")->reply();
                break;*/
         }

    }

    /*消息队列发送模板消息
     *$json类型
     * {
          "tpl": {
            "touser": "OPENID",
            "template_id": "TEMPLATE_ID",
            "url": "http://tt.qiezilife.com",
            "data": {
              "first": {
                "value": "恭喜你退款成功！",
                "color": "#173177"s
              },
              "reason": {
                "value": "未抢购成功",
                "color": "#173177"
              },
              "refund": {
                "value": "999999元",
                "color": "#173177"
              },
              "remark": {
                "value": "备注：如有疑问，请致电13434联系我们，或回复M来了解详情",
                "color": "#173177"
              }
            }
          },
          "openid": [
            "oAJYQv_H82F8keva59hnSxxjbvkA",
            "oAJYQv_H82F8keva59hnSxxjbvkA",
            "oAJYQv_H82F8keva59hnSxxjbvkA",
            "oAJYQv_H82F8keva59hnSxxjbvkA"
          ]
         }
     */
    public function sendTplMsg($template_id,$json,$appId){
        $weObj  = $this->weObj;
        $cache = $this->cache;
        //$reidsKey = C("SEND_TPL_REDIS_KEY");
        //调用模板id缓存，调用接口一次生成一个模板id
        $key = "WxComponentTemplateId_".$appId."_".$template_id;
        $tid =  $this->cache->get($key);
        if(!$tid){
            $tid = $weObj->addTemplateMessage($template_id);
            $this->cache->set($key, $tid,10 * 12 * 30 * 24 * 60 * 60);
        }
        $json_replace = str_replace("TEMPLATE_ID",$tid,$json);
        $allArr = json_decode($json_replace,true);
        $tplArr = $allArr['tpl'];
        foreach($allArr['openid'] as $k => $openid){
            $tpl = str_replace("OPENID",$openid,json_encode($tplArr,JSON_UNESCAPED_UNICODE));
           // $cache::rPush($reidsKey,$tpl);
            $weObj->sendTemplateMessage(json_decode($tpl,true));
        }

       // $weObj->sendTemplateMessage($data);
    }



    /**扫描分类处理事件
     * @param $weObj
     * @param $appid
     */
    protected function geteventmsg($weObj,$appid){
        $data = $weObj->getRevData();
        $ev = $data['Event'];
        switch($ev){
            case "subscribe"://用户未关注时，进行关注后的事件推送
                //获取用户信息
                $userObj = $weObj->getUserInfo($data['FromUserName']);
                //存储用户信息
                $this->storeUserData($userObj,$data['FromUserName']);
                if(isset($data['EventKey'])){//扫描带参二维码关注
                    $scene_arr = explode("_",$data['EventKey']);
                    //场景id
                    $scene_id = $scene_arr[1];
                    $this->sendMsg($weObj,$appid,$scene_id);
                }else{//常规关注
                    $weObj->text(" ")->reply();
                }
                break;
            case  "SCAN"://用户已关注时的事件推送
                $scene_id = $data['EventKey'];
                $this->sendMsg($weObj,$appid,$scene_id);
                break;
            case "LOCATION"://上报地理位置事件

                break;
            case "CLICK"://点击菜单拉取消息时的事件推送

                break;
            case "VIEW"://点击菜单跳转链接时的事件推送

                break;
        }
    }

    /**根据appid和扫码场景id被动回复消息
     * @param $weObj
     * @param $appid
     * @param $scene_id
     */
    protected function sendMsg($weObj,$appid,$scene_id){
        $weiModel = new \Api\Model\WechatEventReplyMsgModel();
        $data = $weiModel->getReplyContent($appid,$scene_id);
        if($data){
            $type=$data['type'];
            switch($type){
                case "text":
                    $weObj->text($data['content'])->reply();
                    break;
                case "image":
                    $weObj->image($data['content'])->reply();
                    break;
                case "news":
                    $weObj->news(json_decode($data['content']))->reply();
                    break;
            }
        }
    }


    /**用户关注公众号存储用户信息
     * @param $userObj
     * @param $openid
     */
   /* protected function storeUserData($userObj,$openid){
        $weiModel = new \Admin\Model\UsersWeixinModel();
        $userModel = new \Admin\Model\UsersModel();
        if (strlen(trim($userObj['nickname'])) == 0) {
            // no nickname? using default one
            $userObj['nickname'] = '茄子粉';
        }
        $data = array();
        $username = $userObj['nickname'];
        if($userModel->check_username($username)){
            $username .= '_' . rand(1, 999);
        }
        $data['user_name'] = $username;
        $data['password'] = md5(rand(111111, 999999999));
        //$data['avatar_file'] = $userObj['headimgurl'];
        $data['referer_uid'] = 0;
        $data['referer_url'] = "authorizer_subscribe";
        $data['sex'] = $userObj['sex'];
        $data['province'] = $userObj['province'];
        $data['city'] = $userObj['city'];
        $data['country'] = $userObj['country'];
        $data['reg_time'] = time();
        $data['from_type'] = 'weixin';
        $data['from_platform'] = "component";
        //增加第三方平台来源字段
        $data['from_appid'] = $this->appId;
        $uid = $userModel->data($data)->add();
        $data_w['openid'] = $openid;
        $data_w['uid'] = $uid;
        $weiModel->data($data_w)->add();


        $rootPath = realpath(__ROOT__).C('AVATAR_PATH');
        $path = $rootPath.$userModel->get_avatar($uid,'real',1);
        Helper::mkDirs($path);

        $avatar_url = str_replace('wx.qlogo.cn', '180.163.26.115', $userObj['headimgurl']);
        Http::curlDownload($avatar_url,$path.$userModel->get_avatar($uid,'real',2).'.jpg');
        $image = new \Think\Image();
        $size = filesize($path.$userModel->get_avatar($uid,'real',2).'.jpg');
        if($size > 0){
            $image->open($path.$userModel->get_avatar($uid,'real',2).'.jpg');
            $image->thumb(100, 100,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'max',0).'.jpg');
            $image->thumb(50, 50,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'mid',0).'.jpg');
            $image->thumb(32, 32,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'min',0).'.jpg');
            $updateData = array();
            $avatar_file = $userModel->get_avatar($uid,'min',0).'.jpg';
            $updateData['uid'] = $uid;
            $updateData['avatar_file'] = $avatar_file;
            $r = $userModel->save($updateData);
        }
        $where_u = array();
        $where_u['uid'] = $uid;
        $user = $userModel->getUser($where_u);
        $user['openid'] = $openid;
        $uid = $user['uid'];
        $salt = $user['salt'];
        $expire = time()+C('COOKIE_EXPIRE');
        $login_key="login_key_".$this->appId;
        cookie($login_key,null);
        $auth_key =  Helper::get_auth_cookie($user['openid'], $uid, $salt, $expire);
        $expire = C('COOKIE_EXPIRE');
        cookie($login_key, $auth_key, $expire, '/', 'qiezilife.com');
        $redis_key = C('REDIS_PREFIX').C('REDIS_USER_PREFIX').$uid;
        $redis_info = C('REDIS');
        $cacheObj = Cache::getInstance('Redis', $redis_info);
        if(!$cacheObj->exists($redis_key)){
            $cacheObj->set($redis_key,json_encode($user));
        }
        Helper::log('<======cacheObj '.print_r($cacheObj->get($redis_key),ture),'Wx_ticket');
    }*/

    protected function storeUserData($userObj,$openid){
        $weiModel = new \Admin\Model\UsersWeixinModel();
        $where_w = array();
        $where_w["openid"] =  $openid;
        $user_w = $weiModel->getUser($where_w);
        $userModel = new \Admin\Model\UsersModel();
        if(!$user_w){
            if (strlen(trim($userObj['nickname'])) == 0) {
                // no nickname? using default one
                $userObj['nickname'] = '茄子粉';
            }
            $data = array();
            $username = $userObj['nickname'];
            if($userModel->check_username($username)){
                $username .= '_' . rand(1, 999);
            }
            $data['user_name'] = $username;
            $data['password'] = md5(rand(111111, 999999999));
            //$data['avatar_file'] = $userObj['headimgurl'];
            $data['referer_uid'] = 0;
            $data['referer_url'] = "authorizer_subscribe";
            $data['sex'] = $userObj['sex'];
            $data['province'] = $userObj['province'];
            $data['city'] = $userObj['city'];
            $data['country'] = $userObj['country'];
            $data['reg_time'] = time();
            $data['from_type'] = 'weixin';
            $data['from_platform'] = "component";
            //增加第三方平台来源字段
            $data['from_appid'] = $this->appId;
            $uid = $userModel->data($data)->add();
            $data_w['openid'] = $openid;
            $data_w['uid'] = $uid;
            $weiModel->data($data_w)->add();


            $rootPath = realpath(__ROOT__).C('AVATAR_PATH');
            $path = $rootPath.$userModel->get_avatar($uid,'real',1);
            Helper::mkDirs($path);

            $avatar_url = str_replace('wx.qlogo.cn', '180.163.26.115', $userObj['headimgurl']);
            Http::curlDownload($avatar_url,$path.$userModel->get_avatar($uid,'real',2).'.jpg');
            $image = new \Think\Image();
            $size = filesize($path.$userModel->get_avatar($uid,'real',2).'.jpg');
            if($size > 0){
                $image->open($path.$userModel->get_avatar($uid,'real',2).'.jpg');
                $image->thumb(100, 100,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'max',0).'.jpg');
                $image->thumb(50, 50,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'mid',0).'.jpg');
                $image->thumb(32, 32,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'min',0).'.jpg');
                $updateData = array();
                $avatar_file = $userModel->get_avatar($uid,'min',0).'.jpg';
                $updateData['uid'] = $uid;
                $updateData['avatar_file'] = $avatar_file;
                $r = $userModel->save($updateData);
            }
        }else{
            $uid = $user_w['uid'];
        }
        $where_u = array();
        $where_u['uid'] = $uid;
        $user = $userModel->getUser($where_u);
        $user['openid'] = $openid;
        $uid = $user['uid'];
        $salt = $user['salt'];
        $expire = time()+C('COOKIE_EXPIRE');
        $login_key="login_key_".$this->appId;
        cookie($login_key,null);
        $auth_key =  Helper::get_auth_cookie($user['openid'], $uid, $salt, $expire);
        $expire = C('COOKIE_EXPIRE');
        cookie($login_key, $auth_key, $expire, '/', 'qiezilife.com');
        $redis_key = C('REDIS_PREFIX').C('REDIS_USER_PREFIX').$uid;
        $redis_info = C('REDIS');
        $cacheObj = Cache::getInstance('Redis', $redis_info);
        if(!$cacheObj->exists($redis_key)){
            $cacheObj->set($redis_key,json_encode($user));
        }
    }

}